export function getPhoneNum() {
 
  // 获取渠道号
  let number = ''; // 默认渠道号
  // 获取当前运行环境
  const platform = uni.getSystemInfoSync().platform.toLowerCase();
  const uniPlatform = uni.getSystemInfoSync().uniPlatform;
  // console.log(uniPlatform);
  // 微信端
  switch(uniPlatform){
    case 'mp-weixin':
      number = 'mp-weixin'; 
      break;
    case 'web':
      let userAgent = navigator.userAgent.toLowerCase()
      if (userAgent.match(/MicroMessenger/i) == 'micromessenger') { // 微信
        number = '101'
      } else if (userAgent.match(/android_hnrcc/i) == 'android_hnrcc' || userAgent.match(/ios_hnrcc/i) == 'ios_hnrcc') { // 手机银行
        number = '102'
      } else {
        number = '110'
      }
      break;
  }
  
  return number;
}

// 获取手机设备信息
export function getMobileNameFc() {
  // 获取初始信息
  var app = navigator.appVersion
  //    根据括号进行分割
  var left = app.indexOf('(')
  var right = app.indexOf(')')
  var str = app.substring(left + 1, right)
  var Str = str.split(';')
  var MobileType = Str[0]
  // 手机型号--苹果 iPhone
  var Mobile_Iphone = Str[0]
  // 手机型号--安卓
  var Mobile_Android = Str[2]
  // 针对红米手机等特殊型号处理 匹配字符
  var res = /Android/
  var reslut = res.test(Mobile_Android)
  var MobileName
  // 根据设备型号判断设备系统
  if (MobileType == 'iPhone') {
    MobileName = Mobile_Iphone + '' + Str[1].substring(4, 19)
  } else if (MobileType == 'Linux') {
    if (reslut) {
      MobileName = Str[4].substring(0, 9) + '' + Str[2]
    } else {
      MobileName = Mobile_Android.substring(0, 9) + '' + Str[1]
    }
  } else if (MobileType == 'iPad') {
    MobileName = Str[0] + ';' + Str[1].substring(4, 12)
  }
  return MobileName
}
// 获取设备操作系统
export function BrowserType() {
  const ua = navigator.userAgent.toLowerCase();
  const testUa = regexp => regexp.test(ua);
  const testVs = regexp => (ua.match(regexp) + "").replace(/[^0-9|_.]/ig, "").replace(/_/ig, ".");
  let system = "unknown";
  if (testUa(/windows|win32|win64|wow32|wow64/ig)) {
    system = "windows"; // window系统
  } else if (testUa(/macintosh|macintel/ig)) {
    system = "osx"; // osx系统
  } else if (testUa(/x11/ig)) {
    system = "linux"; // linux系统
  } else if (testUa(/android|adr/ig)) {
    system = "android"; // android系统
  } else if (testUa(/ios|iphone|ipad|ipod|iwatch/ig)) {
    system = "ios"; // ios系统
  }
  let systemVs = 'unknown'
  if (system === "osx") {
    systemVs = testVs(/os x [\d._]+/ig);
  } else if (system === "android") {
    systemVs = testVs(/android [\d._]+/ig);
  } else if (system === "ios") {
    systemVs = testVs(/os [\d._]+/ig);
  }
  // 获取到system、systemVs
  return Object.assign({
    system, // windows osx linux android ios
    systemVs
  })
}
// 转树形数组结构
export function toTree(data) {
  let result = []
  if (!Array.isArray(data)) {
    return result
  }
  data.forEach((item) => {
    delete item.children
  })
  let map = {}
  data.forEach((item) => {
    map[item.itemCode] = item
  })
  data.forEach((item) => {
    let parent = map[item.parentCode]
    if (parent) {
      (parent.children || (parent.children = [])).push(item)
    } else {
      result.push(item)
    }
  })
  return result
}

/*
 * 数字金额千分小数点格式化
 * 参数说明：
 * number：要格式化的数字
 * * decimals：保留几位小数
 * * dec_point：小数点符号
 * * thousands_sep：千分位符号
 * */
export function numberFormat(number, decimals, dec_point, thousands_sep) {
  number = (number + "").replace(/[^0-9+-Ee.]/g, "")
  var n = !isFinite(+number) ? 0 : +number,
    prec = !isFinite(+decimals) ? 2 : Math.abs(decimals),
    sep = typeof thousands_sep === "undefined" ? "," : thousands_sep,
    dec = typeof dec_point === "undefined" ? "." : dec_point,
    s = "",
    toFixedFix = function (n, prec) {
      var k = Math.pow(10, prec)
      return "" + Math.ceil(n * k) / k
    };

  s = (prec ? toFixedFix(n, prec) : "" + Math.round(n)).split(".")
  var re = /(-?\d+)(\d{3})/
  while (re.test(s[0])) {
    s[0] = s[0].replace(re, "$1" + sep + "$2")
  }

  if ((s[1] || "").length < prec) {
    s[1] = s[1] || ""
    s[1] += new Array(prec - s[1].length + 1).join("0")
  }
  return s.join(dec)
}

// 数字信息脱敏处理
//before前面保留几位
//after后面保留几位
export function sensitiveField(field, before, after) {
  if (!field) {
    return ''
  }
  field = String(field)

  // 匹配中文、英文、数字
  const regItem = '[\u4e00-\u9fa5a-zA-Z0-9]'
  const regExp = `(${regItem}{${before}})${regItem}*(${regItem}{${after}})`
  const reg = new RegExp(regExp)

  return field.replace(reg, '$1**********$2')
}

// 姓名脱敏
export function noPassByName(str) {
  if (str != null && str != undefined) {
    if (str.length <= 3) {
      return str.substring(0, 1) + '*' + str.substring(2, str.length)
    } else if (str.length > 3 && str.length <= 6) {
      return str.substring(0, 1) + '**' + str.substring(3, str.length)
    }
  } else {
    return ''
  }
}

export function getArrVal(arr, key) {
  let val = "";
  if (arr.length > 0) {
    arr.forEach(v => {
      if (key == v.itemCode || key == v.value || key == v.code || key == v.id) {
        val = v.itemText || v.label;
      }
    });
  }
  return val;
}

export function getArrKey(arr, val) {
  let key = "";
  if (arr.length > 0) {
    arr.forEach(v => {
      if (val == v.itemText || val == v.label) {
        key = v.itemCode || v.value || v.code || v.id;
      }
    });
  }
  return key;
}

//判断传入的值是否为空的
export function isEmpty(val) {
  if (val === undefined) {
    return false;
  } else if (val === null) {
    return false;
  } else if (Object.prototype.toString.call(val) === "[object Array]") {
    if (val.length === 0) {
      return false;
    }
  } else if (Object.prototype.toString.call(val) === "[object Object]") {
    if (Object.keys(val).length === 0) {
      return false;
    }
  } else if (typeof val === "string") {
    if (val.trim().length === 0) {
      return false;
    }
  } else if (isNaN(val)) {
    return false;
  }
  return true
}

// arr=[{tip:'',value:''}]
export function testEmpty(arr) {
  let tip = '';
  let flag = true;
  for (let i = 0; i < arr.length; i++) {
    let item = arr[i];
    if (!isEmpty(item.value)) {
      flag = false;
      tip = item.tip;
      break;
    }
  }
  return {
    tip,
    flag
  }
}

//去除字符串空格
export function removeSpace(str) {
  str = str.toString();
  return str.replace(/\s/g, '');
}
//限制输入字数(空格不算字数)
export function limitWordNum_allowSpace(str, maxNum) {
  str = str.toString();
  let spaceNum = 0;
  for (let i = 0; i < str.length; i++) {
    let letter = str[i];
    if (letter === ' ') {
      spaceNum++;
    }
  }
  if (str.length - spaceNum > maxNum) {
    str = str.slice(0, maxNum + spaceNum);
  }
  return str;
}
//限制输入字数(空格算字数)
export function limitWordNum(str, maxNum) {
  str = str.toString();
  if (str.length > maxNum) {
    str = str.slice(0, maxNum);
  }
  return str;
}

// 去抖函数：处理频繁调用问题
export function debounce(method, delay) {
  var timer = null;
  return function () {
    var ctx = this;
    var args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
      method.apply(ctx, args);
    }, delay)
  }
}

// 节流函数：处理频繁调用问题
export function throttle(func, duration) {
  var firstTime = new Date();
  return function () {
    var nextTime = new Date();
    var context = this;
    var args = arguments;
    if (nextTime - firstTime > duration) {
      func.apply(context, args);
      firstTime = nextTime;
    }
  }
}

//获取两个字符之间的字符串内容
//border为'()'、'[]'、"''"等；
export function getMiddleContent(string, border) {
  border = border.toString().trim();
  if (border.length < 2) {
    return '';
  }
  if (!string) {
    return '';
  }
  if (typeof string !== 'string') {
    return '';
  }
  if (!string.includes(border[0]) || !string.includes(border[1])) {
    return string;
  }
  let regstr = '\\' + border[0] + '(.+?)' + '\\' + border[1]; //加?为惰性匹配
  // let regstr = '\\' + border[0] + '((?:.|\\n)+?)' + '\\' + border[1];
  let reg = new RegExp(regstr, "g");

  let res = reg.exec(string);
  if (res && res[1]) {
    return res[1];
  } else {
    return '';
  }
}

// 毫秒数转成指定格式字符串 
//time为毫秒数，format为格式字符串，例如'yyyy-MM-dd'
export function dateFormat(time, format = 'yyyy-MM-dd') {
  const t = new Date(time);
  const tf = function (i) {
    return (i < 10 ? '0' : '') + i;
  };
  return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {
    switch (a) {
      case 'yyyy':
        return tf(t.getFullYear());
        // break;
      case 'MM':
        return tf(t.getMonth() + 1);
        // break;
      case 'mm':
        return tf(t.getMinutes());
        // break;
      case 'dd':
        return tf(t.getDate());
        // break;
      case 'HH':
        return tf(t.getHours());
        // break;
      case 'ss':
        return tf(t.getSeconds());
        // break;
    }
  });
}



//在指定父元素的最后面插入新建的元素
//tagName，新建元素的标签名字符串
//options，新元素的配置对象
// options={
//     css:字符串或对象
//     props:对象，新元素的属性
// }
//father， 父元素，不传则不插入
export function appendChild(tagName, options, father) {
  let newElement = createElement(tagName, options)
  if (father) {
    father.appendChild(newElement);
  }
  return newElement;
}

//在指定父元素的最前面插入新建的元素
//tagName，新建元素的标签名字符串
//options，新元素的配置对象
//father 父元素，不传则不插入
export function insertBefore(tagName, options, father) {
  let newElement = createElement(tagName, options);
  if (father) {
    if (father.childNodes.length === 0) {
      father.appendChild(newElement);
    } else {
      father.insertBefore(newElement, father.childNodes[0]);
    }

  }
  return newElement;
}


function createElement(tagName, options) {
  var svgTags = ['svg', 'g', 'path', 'filter', 'animate', 'marker', 'line', 'polyline', 'rect', 'circle', 'ellipse', 'polygon'];
  let newElement;
  if (svgTags.indexOf(tagName) >= 0) {
    newElement = document.createElementNS("http://www.w3.org/2000/svg", tagName);
  } else {
    newElement = document.createElement(tagName);
  }
  if (options) {
    if (options.css) {
      if (typeof options.css == 'string') {
        newElement.style.cssText = options.css
      } else if (Object.prototype.toString.call(options.css) === '[object Object]') {
        let cssText = '';
        for (var key in options.css) {
          let str = key + ":" + options.css[key] + ";";
          cssText += str;
        }
        newElement.style.cssText = cssText;
      }

    }
    if (options.props) {
      setAttribute(newElement, options.props)
    }
  }
  return newElement
}

function setAttribute(ele, props) {
  for (var key in props) {
    ele.setAttribute(key, props[key])
  }
}

//从location中获取query
export function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  return (false);
}

//根据时间字符串返回时间值,时间字符串格式为'2021-11-21'
export function getTimeByDate(timeStr) {
  var timeArr = timeStr.split("-");
  var year = Number(timeArr[0]);
  var month = Number(timeArr[1]);
  var day = Number(timeArr[2]);
  var timeVal = new Date(year, month - 1, day).getTime();
  return timeVal;
}

// 判断是否过期,传入截止日期，时间字符串格式为'2021-11-21'
export function isOverDeadline(timeStr) {
  if (!timeStr) {
    return false;
  }
  var endTimeArr = timeStr.split('-');
  var year = Number(endTimeArr[0]);
  var month = Number(endTimeArr[1]);
  var day = Number(endTimeArr[2]);
  var endTimeVal = new Date(year, month - 1, day).getTime();
  var nowTimeVal = new Date().getTime();
  return nowTimeVal - endTimeVal > 0
}

// 字符串str1中是否包含字符串str2，如果包含就返回去除包含部分后的剩余部分，如果不包含就还是返回自己
export function removeRepeatString(str1,str2){
 let len2=str2.length;
  let i=str1.indexOf(str2);

  if(i>=0){
      return str1.substr(i+len2);
  }else{
      return str1
  }
}

// 原生浏览器窗户是否被激活方法
export function monitorWindowStatus(active, leave) {
  var len=0;
  if(active&&leave){
      len=2
  }else if(!active&&!leave){
      len=0;
  }else{
      len=1;
  }
  // 不同浏览器 hidden 名称
  let hiddenProperty = 'hidden' in document ? 'hidden' :
      'webkitHidden' in document ? 'webkitHidden' :
      'mozHidden' in document ? 'mozHidden' :
      null;
  // 不同浏览器的事件名
  let visibilityChangeEvent = hiddenProperty.replace(/hidden/i, 'visibilitychange');
  let onVisibilityChange = function () {
      if (!document[hiddenProperty]) {
         
          if(active){
              active();
              len--
          }
      } else {
         
          if(leave){
              leave();
              len--
          }
      }
      if(len==0){
          document.removeEventListener(visibilityChangeEvent, onVisibilityChange); // 移除元素事件句柄
      }
  }
  document.addEventListener(visibilityChangeEvent, onVisibilityChange); // 添加元素事件句柄
}

export async function compressImg(base64String, w, quality) {
  var getMimeType = function(urlData) {
      var arr = urlData.split(',')
      var mime = arr[0].match(/:(.*?);/)[1]
      return mime
  }
  var newImage = new Image()
  var imgWidth, imgHeight

  var promise = new Promise((resolve) => (newImage.onload = resolve))
  newImage.src = base64String
  return await promise.then(() => {
      imgWidth = newImage.width
      imgHeight = newImage.height
      var canvas = document.createElement('canvas')
      var ctx = canvas.getContext('2d')
      if (Math.max(imgWidth, imgHeight) > w) {
          if (imgWidth > imgHeight) {
              canvas.width = w
              canvas.height = (w * imgHeight) / imgWidth
          } else {
              canvas.height = w
              canvas.width = (w * imgWidth) / imgHeight
          }
      } else {
          canvas.width = imgWidth
          canvas.height = imgHeight
      }
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      ctx.drawImage(newImage, 0, 0, canvas.width, canvas.height)
      var base64 = canvas.toDataURL(getMimeType(base64String), quality)
      // console.log('xxx', base64)
      let imData = base64.split('base64,')
      return imData[1]
  })
}

